package com.sunday.gateway.security.authentication;

import com.sunday.common.core.enums.ErrorCodeEnum;
import com.sunday.common.core.remoting.rest.response.RestResponse;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * json类型响应结果
 *
 * @author sunday
 * @see HttpStatusServerAccessDeniedHandler
 * @since 2024/9/23
 */
public interface JsonBaseAuthenticationHandler {

    default Mono<Void> writeJson(ServerHttpResponse response, ErrorCodeEnum errorCodeEnum) {
        return writeJson(response, RestResponse.error(errorCodeEnum, RestResponse.ShowTypeEnum.SILENT));
    }

    default Mono<Void> writeJson(ServerHttpResponse response, RestResponse<?> restResponse) {
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        DataBuffer buffer = dataBufferFactory.wrap(restResponse.toJson().getBytes(Charset.defaultCharset()));
        return response.writeWith(Mono.just(buffer)).doOnError((_) -> DataBufferUtils.release(buffer));
    }

}
